package com.woyowodaows.activity.mine;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.woyowodaows.R;
import com.woyowodaows.base.BaseActivity;
import com.woyowodaows.bean.home.UserDataBean;
import com.woyowodaows.bean.mine.AddressInfosBean;
import com.woyowodaows.bean.mine.CityBean;
import com.woyowodaows.bean.mine.CountyBean;
import com.woyowodaows.bean.mine.ProvinceBean;
import com.woyowodaows.bean.mine.ProvinceListData;
import com.woyowodaows.bean.mine.UserInfoBean;
import com.woyowodaows.request.HttpAsyncTask;
import com.woyowodaows.request.HttpRequestListener;
import com.woyowodaows.request.InterfaceUrl;
import com.woyowodaows.utils.DisplayUtils;
import com.woyowodaows.utils.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by zys on 2018/9/11.
 * 详细地址 activity_detailed_address
 */

public class DetailedAddressActivity extends BaseActivity {

    @BindView(R.id.et_datialiled_address)
    EditText etDatialiledAddress;//省市区
    @BindView(R.id.cr_address_detail)
    EditText detail;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    private OptionsPickerView optionsPickerView;
    private List<ProvinceBean> options1Items = new ArrayList<>();
    private List<String> options1Item = new ArrayList<>();
    private List<List<String>> options2Item = new ArrayList<>();
    private List<List<List<String>>> options3Item = new ArrayList<>();
    private String mPickAddress;
    private int mOptions1, mOptions2, mOptions3;

    private String details = "";

    private  int      lastAreaId=0;//:11   最后一级地区id
    private  int       areaIdPath=0;//:地区id以,分隔
    private  String    areaNames;//:地区拼接
    private  String    address;//:详细地址
    private String type;
    private String url;
    private AddressInfosBean  addressBean;
    private int  addressId=0;

    Map<String, Object> mparam = new HashMap<String, Object>();
    private boolean isSelect = false;//是否选择
    private UserInfoBean userInfoBean;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    initPickerView();
                    break;
                case 1:
                    Intent intent = new Intent();
                    setResult(202, intent);
                    finish();
                    break;
                case 2:
//                    ToastUtil.show(EditAddressActivity.this,"发生未知错误！");
                    break;
            }

        }
    };


    @Override
    public int getLayoutId() {
        return R.layout.activity_detailed_address;
    }


    @Override
    public void initView() {
        super.initView();
        ButterKnife.bind(this);
        getAddress();
        DisplayUtils.addLayoutListener(rlLayout, tvSubmit);

    }


    @Override
    public void initEvent() {
        super.initEvent();
    }

    @Override
    public void initData() {
        super.initData();
        if(getIntent()!=null){
            type = getIntent().getExtras().getString("ATYPE");
        }
        String title = null;
        if (type != null) {
            if (type.equals("editAdd")) {
                title = "编辑地址";
                tvSubmit.setText("保存");
                addressBean = (AddressInfosBean) getIntent().getExtras().getSerializable("ADDRESS");
                if (addressBean != null) {

//                    mapParameter.put("lastAreaId", lastAreaId);
//                    mapParameter.put("areaIdPath", areaIdPath);//昵称
//                    mapParameter.put("areaNames",mPickAddress);//地区拼接
//                    mapParameter.put("address", address);//详细地址
                    etDatialiledAddress.setText(addressBean.getAreaNames());
                    detail.setText(addressBean.getAddress());
                    mPickAddress=addressBean.getAreaNames();
                    lastAreaId=Integer.valueOf(addressBean.getLastAreaId());
                    areaIdPath=Integer.valueOf(addressBean.getAreaIdPath());
                    addressId=addressBean.getId();
                }

            } else if (type.equals("addAdd")) {
                tvSubmit.setText("添加");
                title = "新建地址";

            }
        }
        setTitleBar(false, title, null, 0, 0, null);
        switch (type){
            case "addAdd":
                //新增地址
                url=InterfaceUrl.SAVEADDRESS;
//                addAddData();
//                updateAddress(url);
                break;
            case "editAdd":
                //编辑
                url=InterfaceUrl.UPDATEADDRESS;
//                eidtAddData();
//                updateAddress(url);
                break;
        }
    }

    private void updateAddress() {



        //        fieldName:email   // email 电子邮箱格式       gender:1男 2女       realname 真实姓名必须是中文     birthday 请确认你输入生日是否正确    nickname:昵称不能为空  avatar: 头像路径不能为空
//        fieldValue:332741160@qq.com
        Map<String, Object> mapParameter = new HashMap<>();
//        lastAreaId:11   最后一级地区id
//        areaIdPath:地区id以,分隔
//        areaNames:地区拼接
//        address:详细地址
        address=detail.getText().toString().trim();
        String  areaDetail=etDatialiledAddress.getText().toString().trim();
        if (TextUtils.isEmpty(areaDetail)) {
            ToastUtil.show_short(mContext, "请选择地址!");
            return;
        }
        if (TextUtils.isEmpty(address)) {
            ToastUtil.show_short(mContext, "请输入详细的地址!");
            return;
        }
        if(type.equals("editAdd")){
            mapParameter.put("id", addressId);
        }
        mapParameter.put("lastAreaId", lastAreaId);
        mapParameter.put("areaIdPath", areaIdPath);//昵称
        mapParameter.put("areaNames",mPickAddress);//地区拼接
        mapParameter.put("address", address);//详细地址
        HttpAsyncTask.getInstance().onPostParam(mContext, "修改中...", true, url, UserDataBean.class, mapParameter, new HttpRequestListener() {
            @Override
            public void onSuccess(Object result) {
                if (result != null) {
                    UserDataBean bean = (UserDataBean) result;
                    if (bean.getResult() == HttpAsyncTask.SUCCESS) {
//                        Intent detailIntent = new Intent();
//                        detailIntent.putExtra("pivAddress", details);
//                        setResult(3, detailIntent);
//
//                        finish();
                         handler.sendEmptyMessage(1);
                        ToastUtil.show(mContext, bean.getMessage());

                    } else {
                        ToastUtil.show(mContext, bean.getMessage());
                    }
                }
            }

            @Override
            public void onError(String message) {
                ToastUtil.show(mContext, message);
            }
        });

    }


    private void initPickViewThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = 0;
                handler.sendMessage(msg);
            }
        }).start();

    }

    private void initPickerView() {
        optionsPickerView = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                mPickAddress = options1Item.get(options1) + " "
                        + options2Item.get(options1).get(options2) + " "
                        + options3Item.get(options1).get(options2).get(options3);
//                provinceText=options1Item.get(options1).getName();//省份
//                cityContent=options2Item.get(options1).get(options2);//城市
//                areaNames=options3Item.get(options1).get(options2).get(options3);//区
                if(options1Items.get(options1).getChild().get(options2).getChild().size()>0){
                    areaIdPath=options1Items.get(options1).getChild().get(options2).getParentId();
                    lastAreaId=options1Items.get(options1).getChild().get(options2).getChild().get(options3).getParentId();
                }else {
                    areaIdPath=options1Items.get(options1).getChild().get(options2).getParentId();
                    lastAreaId=0;
                }
            }
        })
                .setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        TextView sure = (TextView) v.findViewById(R.id.tv_finish);
                        TextView cancel = (TextView) v.findViewById(R.id.iv_cancel);
                        sure.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                optionsPickerView.returnData();
                                optionsPickerView.dismiss();
                                etDatialiledAddress.setText(mPickAddress);
                            }
                        });
                        cancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                optionsPickerView.dismiss();
                            }
                        });
                    }
                })
                .setLineSpacingMultiplier(3.5f)
                .setContentTextSize(20)
                .setSelectOptions(mOptions1, mOptions2, mOptions3)
                .build();
        optionsPickerView.setPicker(options1Item, options2Item, options3Item);


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }



    private void getAddress() {
        Map<String, Object> mapParameter = new HashMap<>();
        HttpAsyncTask.getInstance().onPostParam(this, "...", false, InterfaceUrl.DISTRIBUTIONAREA, ProvinceListData.class, mapParameter, new HttpRequestListener() {
            @Override
            public void onSuccess(Object result) {
                if (result != null) {
                    ProvinceListData bean = (ProvinceListData) result;
                    if (bean.getResult() == HttpAsyncTask.SUCCESS) {
                        options1Items.addAll(bean.getData());
                        if (options1Items != null && options1Items.size() > 0) {
                            for (int i = 0; i < options1Items.size(); i++) {
                                ProvinceBean provinceBean = options1Items.get(i);
                                options1Item.add(provinceBean.getName());
                                List<String> cityList = new ArrayList<>();  //该省的城市列表
                                List<List<String>> p_areaList = new ArrayList<>(); //该省的所有地区列表
                                for (int j = 0; j < provinceBean.getChild().size(); j++) {
                                    CityBean cityBean = provinceBean.getChild().get(j);
                                    String cityName = cityBean.getName();
                                    cityList.add(cityName);
                                    List<String> c_areaList = new ArrayList<>(); //该城市的所有地区
                                    if (options1Items.get(i).getChild().get(j).getChild() == null || options1Items.get(i).getChild().get(j).getChild().size() == 0) {
                                        c_areaList.add("");
                                    } else {
                                        for (int k = 0; k < cityBean.getChild().size(); k++) {
                                            CountyBean countyBean = cityBean.getChild().get(k);
                                            String countyName = countyBean.getName();
                                            c_areaList.add(countyName);
                                        }
                                    }
                                    p_areaList.add(c_areaList);
                                }
                                options2Item.add(cityList);
                                options3Item.add(p_areaList);
                            }
                        }
                    }
                }
                initPickViewThread();
            }

            @Override
            public void onError(String message) {
                ToastUtil.show_short(mContext, message);
            }
        });
    }

    @OnClick({R.id.et_datialiled_address, R.id.tv_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_datialiled_address:
                isSelect=true;
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(etDatialiledAddress.getWindowToken(), 0);
                optionsPickerView.show();
                break;
            case R.id.tv_submit:

                if (TextUtils.isEmpty(detail.getText().toString().trim())) {
                    ToastUtil.show_short(mContext, "详细地址不能为空！");
                    return;
                }
                updateAddress();
                break;
        }
    }
}
